package com.iasku.fragment;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.iasku.constant.Constant;
import com.iasku.iaskueleclass_phone.R;
import com.iasku.iaskueleclass_phone.Status;
import com.iasku.iaskueleclass_phone.activity.UserSettingActivity;
import com.iasku.manager.IaskuManager;
import com.iasku.util.DateUtil;

public class BaseFragment extends Fragment {
    public TextView mBarTitleCenterTv;
    public ImageView mBarSettingIv;
    public TextView mYearStartTv,mMonthStartTv,mDayStartTv;
    public TextView mYearEndTv,mMonthEndTv,mDayEndTv;
    public Button mBarSearchBtn;
    public View mRootView;
    public LinearLayout mStartTimeLayout,mEndTimeLayout;
    public ProgressDialog mProgressDialog;
    public long time_start,time_end;
    public String time_start_text,time_end_text;
    public TextView mBarTitleSubjectTv;
    
    private PopupWindow mSubjectPop;
    private String mSubjectCurrect;
    
    private void initPopupWindow(){
        View viewPop = LayoutInflater.from(getActivity().getApplicationContext()).inflate(R.layout.subject_popup_gridview, null);
        mSubjectPop = new PopupWindow(viewPop);
        mSubjectPop.setWindowLayoutMode(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mSubjectPop.setOutsideTouchable(true);
        GridView mSubjectGv = (GridView) viewPop.findViewById(R.id.subject_choose_gridview);
        String[] mSubjects = getResources().getStringArray(R.array.subject_all_list);
        mSubjectCurrect = IaskuManager.getInstance().getSujectName();
        mSubjectGv.setAdapter(new MyAdapter(getActivity().getApplicationContext(), mSubjects));
    }
    
    private void initView(View view){
        mBarTitleCenterTv = (TextView) view.findViewById(R.id.common_titlebar_title_tv);
        mBarSettingIv = (ImageView) view.findViewById(R.id.common_titlebar_setting_iv);
        mBarSearchBtn = (Button) view.findViewById(R.id.common_titlebar_seach_btn);
        mYearStartTv = (TextView) view.findViewById(R.id.common_titlebar_year_start_tv);
        mMonthStartTv = (TextView) view.findViewById(R.id.common_titlebar_month_start_tv);
        mDayStartTv = (TextView) view.findViewById(R.id.common_titlebar_day_start_tv);
        mYearEndTv = (TextView) view.findViewById(R.id.common_titlebar_year_end_tv);
        mMonthEndTv = (TextView) view.findViewById(R.id.common_titlebar_month_end_tv);
        mDayEndTv = (TextView) view.findViewById(R.id.common_titlebar_day_end_tv);
        mStartTimeLayout = (LinearLayout) view.findViewById(R.id.common_titlebar_time_start_layout);
        mEndTimeLayout = (LinearLayout) view.findViewById(R.id.common_titlebar_time_end_layout);
        mBarTitleSubjectTv = (TextView) view.findViewById(R.id.common_titlebar_subject_tv);
        mBarTitleSubjectTv.setText(IaskuManager.getInstance().getSujectName());
        setDateValue();
        initPopupWindow();
    }
    
    /** 初始化日期 */
    private void setDateValue(){
        setDateStartValue();
        setDateEndValue();
    }
    
    private void setDateStartValue(){
        mYearStartTv.setText(String.valueOf(Constant.YEAR_START) + "年");
        mMonthStartTv.setText(String.valueOf(Constant.MONTH_START + 1));
        mDayStartTv.setText("月" + Constant.DAY_START +"日");
        
    }

    private void setDateEndValue(){
        mYearEndTv.setText(String.valueOf(Constant.YEAR_END) + "年");
        mMonthEndTv.setText(String.valueOf(Constant.MONTH_END + 1));
        mDayEndTv.setText("月" + Constant.DAY_END +"日");
    }
    
    private void showDateStartDialog(){
        DatePickerDialog dialog_start = new DatePickerDialog(getActivity(),
                                new OnDateSetListener(){
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Constant.YEAR_START = year;
                Constant.MONTH_START = monthOfYear;
                Constant.DAY_START = dayOfMonth;
                setDateStartValue();
            }
            
        }, Constant.YEAR_START, Constant.MONTH_START,Constant.DAY_START);
        dialog_start.show();
    }
    
    private void showDateEndDialog(){
        DatePickerDialog dialog_end = new DatePickerDialog(getActivity(), 
                        new OnDateSetListener(){
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Constant.YEAR_END = year;
                Constant.MONTH_END = monthOfYear;
                Constant.DAY_END = dayOfMonth;
                setDateEndValue();
            }
        }, Constant.YEAR_END, Constant.MONTH_END,Constant.DAY_END);
        dialog_end.show();
    }
    
    private void addListener(){
        mStartTimeLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDateStartDialog();
            }
        });
        
        mEndTimeLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDateEndDialog();
            }
        });
        
        mBarSettingIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity().getApplicationContext(),UserSettingActivity.class);
                startActivity(intent);
            }
        });
        
        mBarTitleSubjectTv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showPop(mSubjectPop,v);
            }

        });
    }
    
    private void showPop(PopupWindow popupWindow, View view) {
        if(popupWindow.isShowing()){
            popupWindow.dismiss();
        }else{
            popupWindow.showAsDropDown(view);
        }
    }
    
    private void initTitleBar(){
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setMessage("正在加载...");
        initView(mRootView);
        addListener();
    }
    
    public void initTime(){
        String month1 = Constant.MONTH_START + 1 < 10 ? "0" + (Constant.MONTH_START + 1) : "" + (Constant.MONTH_START + 1);
        String month2 = Constant.MONTH_END + 1 < 10 ? "0" + (Constant.MONTH_END + 1) : "" + (Constant.MONTH_END + 1);
        try{
            String time1 = Constant.YEAR_START + "-" + month1 + "-" + Constant.DAY_START +" 00:00:00";
            String time2 = Constant.YEAR_END + "-" + month2 + "-" + Constant.DAY_END + " 23:59:59";
            time_start = DateUtil.parserStr2Date(time1);
            time_end = DateUtil.parserStr2Date(time2);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
   
    public void initTimeText(){
        String month1 = Constant.MONTH_START + 1 < 10 ? "0" + (Constant.MONTH_START + 1) : "" + (Constant.MONTH_START + 1);
        String month2 = Constant.MONTH_END + 1 < 10 ? "0" + (Constant.MONTH_END + 1) : "" + (Constant.MONTH_END + 1);
        time_start_text = Constant.YEAR_START + "-" + month1 + "-" + Constant.DAY_START;
        time_end_text = Constant.YEAR_END + "-" + month2 + "-" + Constant.DAY_END;
    }
    
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    
    public void initTitleBar(int textId){
        initTitleBar();
        mBarTitleCenterTv.setText(textId);
    }
    
    @SuppressLint("HandlerLeak")
    public Handler mHander = new Handler() {

        public void handleMessage(Message msg) {
            onTaskComplete(msg.what, (Status) msg.obj);
        }
    };

    public int startTask(int taskId) {
        return startTask(taskId, null);
    }

    public int startTask(int taskId, Bundle bundle) {
        onTaskStart(taskId, bundle);
        new Thread(new TaskRunnable(taskId, bundle)).start();
        return taskId;
    }

    public int onTaskStart(int taskId, Bundle bundle) {
        return taskId;
    }

    /**
     * 后台运行
     * 
     * @param taskId
     *            任务ID
     * @param msg
     * @return error code
     */
    public Status onTaskInBackground(int taskId, Bundle bundle) {
        return new Status(0);
    }

    /**
     * 任务结束，UI线程操作
     * 
     * @param taskId
     * @param err
     *            errorCode
     * @return
     */
    public int onTaskComplete(int taskId, Status status) {
        return taskId;
    }

    class TaskRunnable implements Runnable {

        private int taskId;
        private Bundle bundle;

        public TaskRunnable(int id) {
            taskId = id;
        }

        public TaskRunnable(int id, Bundle m) {
            taskId = id;
            bundle = m;
        }

        @Override
        public void run() {
            Status result = onTaskInBackground(taskId, bundle);
            Message msg = mHander.obtainMessage(taskId);
            msg.obj = result;
            msg.sendToTarget();
        }
    }
    
    private class MyAdapter extends BaseAdapter{
        private LayoutInflater mInflater;
        private String[] mSubjects;
        
        public MyAdapter(Context mContext,String[] mSubjects){
            this.mInflater = LayoutInflater.from(mContext);
            this.mSubjects = mSubjects;
        }
        
        @Override
        public int getCount() {
            return mSubjects.length;
        }

        @Override
        public Object getItem(int position) {
            return mSubjects[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if(convertView == null){
                convertView = mInflater.inflate(R.layout.subject_popup_item, null);
                holder = new ViewHolder();
                holder.tvSubject = (TextView) convertView.findViewById(R.id.tv_subject_name);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tvSubject.setText(mSubjects[position]);
            if(mSubjectCurrect.equals(mSubjects[position])){
                holder.tvSubject.setTextColor(getResources().getColor(R.color.main_bottom_blue));
            }else{
                holder.tvSubject.setTextColor(getResources().getColor(R.color.comment_text2_color));
            }
            
            holder.tvSubject.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSubjectPop.dismiss();
                    IaskuManager.getInstance().setSubjectId(position);
                    mBarTitleSubjectTv.setText(mSubjects[position]);
                    mSubjectCurrect = mSubjects[position];
                    MyAdapter.this.notifyDataSetChanged();
                }
            });
            return convertView;
        }
        
        private class ViewHolder {
            TextView tvSubject;
        }
        
    }
}
